// Copyright (c) 2002 HTHK
//******************************************************************/
//Modification History
//******************************************************************/
//CR log no 1054: By Oscar Bai  Date:2003/02//CR log no 1055 : By MLin June 2003
//Update by Poly Li on 2004-3-23 8:52
//******************************************************************/
/*--------------------------------------------------------------
 * Modification History
 *--------------------------------------------------------------
 * CRLOG	: CR1528
 * Fix		: Sox passwd control & add fields company_code, login_trial
 * By		: PH, HPMS
 * Date		: 06-Dec-2005
 *--------------------------------------------------------------
 */
package admin.system.user;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.log4j.Logger;

import java.io.*;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.sql.*;

import com.ffpc.servlet.*;
import com.ffpc.sql.*;
import com.ffpc.struts.StrutsMessage;
import com.ffpc.util.DateFormatter;
import com.system.userMultiRole.UserMultiRoleBean;
import com.system.userMultiRole.UserMultiRoleProcess;

import admin.system.sysparam.*;
import admin.JisEncrypt;
/* CR1528 */
import admin.system.passwdhistory.*;

import org.apache.regexp.RE;
/* CR1528 */
/**
 * A Class class.

 * <P>
 * @author HTHK
 */
 
public class UserServlet
  extends DBServlet {
    
    private RE passwordComplexity1;
    private RE passwordComplexity2;
    private RE passwordComplexity3;
    private Logger logger = Logger.getLogger(getClass());
    
    /**
     * Trick to allow user to update password when it is expired. At that moment 
     * the user object in session is not authenticated.
     */
    @Override
    protected boolean isLogin() {
        return getUser() != null;
    }

@Override
protected String perform(  HttpServletRequest request,
                             HttpServletResponse response,
                             StrutsMessage message)
    throws  ServletException,
            IOException,
            SQLException,
            DataException,
            Exception
  {
     	boolean debug = false;
     	Statement statement = null;
    	ResultSet resultSet = null;
    	statement = this.getConnection().createStatement();
     
     //CR log no 1054 begin of:
      String changePasswd = "N" ;
      String expiryPasswd = "N";
      String tempStr="";
      int tempInt=0;
      
      Date tempDate=null;

      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss",Locale.US);
      Calendar tempCalendar=new GregorianCalendar();

     //CR log no 1054 end of:

      String action = new String(request.getParameter("formAction"));
	if(debug)
		System.out.println("UserServlet.java -- action is : "+action);
     //CR log no 1054 begin of:
      changePasswd = request.getParameter("changePasswd") ;
      expiryPasswd = request.getParameter("expiryPasswd") ;
      
      if ( changePasswd == null  )
      {
          changePasswd = "N" ;
      }    

      if ( expiryPasswd == null  )
      {
          expiryPasswd = "N" ;
      }      
     //CR log no 1054 end of:

      UserBean user = UserProcess.createBean();
      user.setUser_id(request.getParameter("user_id"));
      user.setUser_name(request.getParameter("user_name"));
      user.setUser_des(request.getParameter("user_des"));

    //CR log no 1054 begin of: adjudge wether user want to change passwd ,
    //       I set a hidden param in User.jsp, Check the passws is changed 

      if (request.getParameter("oldpasswd")!=null){
        if (!(request.getParameter("oldpasswd").equals(request.getParameter("passwd")))){
         
          //CR Log no:no begin of: Add JisEncrypt,Encrypt passwrod

          JisEncrypt jis_encrypt = new JisEncrypt(this.getConnection());
          tempStr= jis_encrypt.Encrypt(request.getParameter("passwd"));
          user.setPasswd(tempStr);

          //CR Log no:no end of
          
        }else{
          user.setPasswd(request.getParameter("passwd"));
        }
      }else{
         user.setPasswd(request.getParameter("passwd"));
      }

   //CR log no 1054 end of:      

   //CR log no 1054 begin of: Set Expiry date.
   //if user don't set Expirte Date then System auto set it 
      if (changePasswd.equals("Y")||expiryPasswd.equals("Y")){

        //CR log no:no begin of:Get the system parameter from table jis_s_system_paramete
        SysParamBean sysParam = SysParamProcess.createBean();
        
        //"expiry_days" is parameter name, Get parameter value by parameter name
        sysParam.setSys_Param_name("expiry_days");
        SysParamBean[] sysParams = SysParamProcess.find(this.getConnection(),sysParam);
        if (sysParams==null || sysParams.length==0)
        {
           message.setMessage("No system parameter expiry_days, please input it.");
           return "system/User.jsp";
        }else{
           tempStr=((SysParam)sysParams[0]).getSys_Param_value();
           tempInt=Integer.parseInt(tempStr);
        }
        //CR log no:no end of

        tempCalendar.setTime(new Date());
        tempCalendar.add(Calendar.DAY_OF_MONTH,tempInt);

        ///2003-3-7
//        tempStr=sdf.format(tempCalendar.getTime());
        ////        

        tempStr=DateFormatter.format(tempCalendar.getTime());
        
        user.setPass_exp_date(tempStr);
      }else{

        user.setPass_exp_date(request.getParameter("pass_exp_date"));

      }
   //CR log no 1054 end of
      
//-----------Start modify by Poly-------------
//---------Add by Poly Li,for get more role_id----------
      UserMultiRoleBean userMultiRole = UserMultiRoleProcess.createBean();

    String[] gStrRoleID = null;

	if(expiryPasswd.equals("N"))
		if(changePasswd.equals("N") )
		{
			if(request.getParameterValues("role_id") != null)
			{
	      		gStrRoleID = request.getParameterValues("role_id");
				
				userMultiRole.setUser_id(request.getParameter("user_id"));
				userMultiRole.setCrt_user(getUser().getUser_id());
				userMultiRole.setCrt_date(DateFormatter.format(this.getDate()));
				userMultiRole.setUpd_user(getUser().getUser_id());
				userMultiRole.setUpd_date(DateFormatter.format(this.getDate()));
			}
		}
		else
			user.setRole_id(request.getParameter("role_id"));

//End add by Poly
      
      user.setCost_center_id(request.getParameter("cost_center_id"));
      user.setEmail(request.getParameter("email"));
      user.setMobile(request.getParameter("mobile"));
      user.setStaff_id(request.getParameter("staff_id"));
      user.setActive(request.getParameter("active"));
      user.setUpd_user(getUser().getUser_id());
      user.setUpd_date(DateFormatter.format(this.getDate()));

   //CR log no 1054 begin of:  set the deacivated by and the deactivated date 
   //                          when the inactive date was changed
      user.setInactive_date(request.getParameter("inactive_date"));

      if (request.getParameter("inactive_date")!=null){
        if (!(request.getParameter("inactive_date").equals(request.getParameter("old_inactive_date")))){
          user.setDeactivated_by(getUser().getUser_id());
          user.setDeactivated_date(DateFormatter.format(this.getDate()));
        }
      } 
   //CR log no 1054 end of
   // CR 1055 by MLIN on June 2003  
    user.setRequest_group(request.getParameter("request_group"));
   // End of CR 1055
   /* CR1528 */
    user.setCompany_code(request.getParameter("company_code"));
	user.setLogin_trial(request.getParameter("login_trial"));
   /* CR1528 */

      if (action.trim().equalsIgnoreCase("Create"))
      {
         user.setCrt_user(getUser().getUser_id());
         user.setCrt_date(DateFormatter.format(this.getDate()));
        if (UserProcess.insert(this.getConnection(),user)>0)
        {
//Add by Poly, for loop insert role id into jis_s_user_role table
		
			for(int i = 0;i <gStrRoleID.length; i++)
			{
				userMultiRole.setRole_id(gStrRoleID[i]);
				//System.out.println("i="+i+" role id is : "+gStrRoleID[i]);
		        	UserMultiRoleProcess.insert(this.getConnection(),userMultiRole);
			}
			/* CR1528 */
			PasswdHistoryProcess.updateOldestRecord(this.getConnection(), user.getUser_id(), user.getPasswd(),  DateFormatter.format_n(this.getDate()) );
			/* CR1528 */
			message.setMessage("Save successfully.");
//End Add by Poly , on 2004-4-23 9:05
		}
        else
            message.setMessage("Save failure");
      }
      else if (action.trim().equalsIgnoreCase("Update"))
      {
/*
        if (UserProcess.update(this.getConnection(),user)>0)
            message.setMessage("Save successfully.");
        else
            message.setMessage("Save failure.");
*/

//Add by Poly , on 2004-4-23 9:07
		if(expiryPasswd.equals("N"))
		{
			if(changePasswd.equals("N"))
			{
				try
				{
					String del_user = "delete from jis.jis_s_user_role where user_id ='"+userMultiRole.getUser_id()+"'";
					if(debug)
						System.out.println("UserServlet.java -- del_user is : "+del_user);
					statement.executeUpdate(del_user);
				}
				catch(Exception eee)
				{
				        logger.error("", eee);
					message.setMessage("Save failure.");
				}
	
			user.setCrt_user(getUser().getUser_id());
	         	user.setCrt_date(DateFormatter.format(this.getDate()));
//Insert into multi role 
				/* CR1528 */
				if( PasswdHistoryProcess.isExist(this.getConnection(), user.getUser_id(), request.getParameter("passwd") ) ){
					message.setMessage("Save failure - cannot re-use latest password(s) " );
					throw new DataException("Save failure - cannot re-use latest password(s) ");
				}
				/* CR1528 */
				if(UserProcess.delete(this.getConnection(),user)>0 )
					if (UserProcess.insert(this.getConnection(),user)>0)
					{	
						for(int i = 0;i <gStrRoleID.length; i++)
						{
							userMultiRole.setRole_id(gStrRoleID[i]);
						       	UserMultiRoleProcess.insert(this.getConnection(),userMultiRole);
						}
						message.setMessage("Save successfully.");
					}
					else
						message.setMessage("Save failure.");
				else
					message.setMessage("Save failure.");
			}
			else
			{
                            final String newPassword = request.getParameter("passwd");
                            if (!this.isPasswordComplexityEnough(newPassword)) {
                                final String msg = "Save failure - new password must contain digits and letters of upper and lower case";
                                message.setMessage(msg);
                                throw new DataException(msg);
                            }
				/* CR1528 */
				if( PasswdHistoryProcess.isExist(this.getConnection(), user.getUser_id(), request.getParameter("passwd") ) ){
					message.setMessage("Save failure - cannot re-use latest password(s) " );
					throw new DataException("Save failure - cannot re-use latest password(s) ");
				}
				/* CR1528 */
				try
				{
					String upd_pass = " update jis.jis_s_user ";
						upd_pass += " set passwd = '"+user.getPasswd()+"'";
						upd_pass += " , pass_exp_date=to_date('"+user.getPass_exp_date()+"','DD/MM/YYYY')";
						upd_pass += " where user_id='"+user.getUser_id()+"'";
					if(debug)
						System.out.println("UserServlet.java , upd_pass is : "+upd_pass);
					statement.executeUpdate(upd_pass);
					/* CR1528 */
					PasswdHistoryProcess.updateOldestRecord(this.getConnection(), user.getUser_id(), user.getPasswd(), DateFormatter.format_n(this.getDate()) );
					/* CR1528 */
					message.setMessage("Save sucessful.");
				}
				catch(Exception eee)
				{
				        logger.error("", eee);
					message.setMessage("Save failure.");
				}
			}
		}
		else { //expiryPasswd=Y
				/* CR1528 */
				if( PasswdHistoryProcess.isExist(this.getConnection(), user.getUser_id(), request.getParameter("passwd") ) ){
					throw new DataException("Save failure - cannot re-use latest password(s) ");
				}
				/* CR1528 */
				String upd_pass = " update jis.jis_s_user ";
					upd_pass += " set passwd = '"+user.getPasswd()+"'";
					upd_pass += " , pass_exp_date=to_date('"+user.getPass_exp_date()+"','DD/MM/YYYY')";
					upd_pass += " where user_id='"+user.getUser_id()+"'";
				if(debug)
					System.out.println("UserServlet.java , upd_pass is : "+upd_pass);

				logger.info("Updating password of user " + user.getUser_id());
				logger.debug("upd_pass = " + upd_pass);

				int rowsUpdated = statement.executeUpdate(upd_pass);

				if (rowsUpdated == 0) {
				    throw new DataException("Update failed - no row updated");
				}
                                if (rowsUpdated > 1) {
                                    throw new DataException("Update failed - multiple rows updated");
                                }
				
				/* CR1528 */
				PasswdHistoryProcess.updateOldestRecord(this.getConnection(), user.getUser_id(), user.getPasswd(), DateFormatter.format_n(this.getDate()) );
				/* CR1528 */
				//message.setMessage("Save sucessful.");
				user.setAuthenticated(true);
				request.getSession().setAttribute("user", user);
			}
      }
      else if (action.trim().equalsIgnoreCase("Delete"))
      {
/*
        if (UserProcess.delete(this.getConnection(),user)>0)
            message.setMessage("Delete successfully.");
        else
            message.setMessage("Delete failure.");
*/

			try
			{
				String del_user = "delete from jis.jis_s_user_role where user_id ='"+userMultiRole.getUser_id()+"'";
				statement.executeUpdate(del_user);
				if (UserProcess.delete(this.getConnection(),user)>0)
		            message.setMessage("Delete successfully.");
		        else
		            message.setMessage("Delete failure.");
			}
			catch(Exception eee)
			{
				message.setMessage("Delete failure.");
			}
	        
//End modified by Poly Li, on 2004-4-23 9:06
////////////////////////////////////////////
	        
		}

      else
            message.setMessage("No action mapped!");

    //CR log no 1054 begin of: if change passwd then return 
    //                         if cnange expiry Date then to main menu
    //                         if mantinace user then to usersercher
      if ( changePasswd.equals("Y") ) 
      {
         return "system/ChangePassword.jsp" ;
      }
      else if (expiryPasswd.equals("Y"))
      {
         return "servlet/admin.menu.MenuServlet" ;
      }
      else
      {
         return "system/UserSearch.jsp";
      }
     //CR log no 1054 end of    

  }
  
    private boolean isPasswordComplexityEnough(String newPassword) {
        

        if (this.passwordComplexity1 == null) {
            passwordComplexity1 = new RE("\\d+");
            passwordComplexity2 = new RE("[a-z]+");
            passwordComplexity3 = new RE("[A-Z]+");
        }
        if (newPassword != null && !newPassword.trim().equals("")) {
            if (passwordComplexity1.match(newPassword)) {
                if (passwordComplexity2.match(newPassword)) {
                    if (passwordComplexity3.match(newPassword)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}


